package cn.start6.dahuacontrol.controller;

import cn.start6.dahuacontrol.lib.NetSDKLib;
import cn.start6.dahuacontrol.utils.response.Result;
import com.sun.jna.Pointer;
import org.springframework.web.bind.annotation.*;
import cn.start6.dahuacontrol.module.*;

import javax.swing.*;

@RestController
public class loginController {
    DisConnect disConnect = new DisConnect();
    HaveReConnect haveReConnect = new HaveReConnect();

    @GetMapping("/login")
    public Result login(@RequestParam(name = "ip") String m_strIp, @RequestParam(name = "port") int m_nPort, @RequestParam(name = "username") String m_strUser, @RequestParam(name = "password") String m_strPassword){
        try {
            // init login
            boolean initStatus = LoginModule.init(disConnect, haveReConnect);
            // init success
            if(initStatus) {
                long loginStatus = LoginModule.login(m_strIp, m_nPort, m_strUser, m_strPassword);
                // login success
                if(loginStatus != 0) {
                    System.out.println("start");
                    System.out.println(loginStatus);
                    return Result.success(loginStatus);
                }else{
                    return Result.failure();
                }
            }
        }catch(Exception e) {
            System.out.println(e);
        }
        return Result.success(0);
    }

    @GetMapping("/logout")
    public boolean logout() {
        LoginModule.logout();
        LoginModule.cleanup();
        return true;
    }

    // private static class

    /////////////////面板///////////////////
    // 设备断线回调: 通过 CLIENT_Init 设置该回调函数，当设备出现断线时，SDK会调用该函数
    private static class DisConnect implements NetSDKLib.fDisConnect {
        public void invoke(NetSDKLib.LLong m_hLoginHandle, String pchDVRIP, int nDVRPort, Pointer dwUser) {
            System.out.printf("Device[%s] Port[%d] DisConnect!\n", pchDVRIP, nDVRPort);
            // 断线提示
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    System.out.printf("Device ReLoading...");
                }
            });
        }
    }

    // 网络连接恢复，设备重连成功回调
    // 通过 CLIENT_SetAutoReconnect 设置该回调函数，当已断线的设备重连成功时，SDK会调用该函数
    private static class HaveReConnect implements NetSDKLib.fHaveReConnect {
        public void invoke(NetSDKLib.LLong m_hLoginHandle, String pchDVRIP, int nDVRPort, Pointer dwUser) {
            System.out.printf("ReConnect Device[%s] Port[%d]\n", pchDVRIP, nDVRPort);

            // 重连提示
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    System.out.printf("Reconnect loading....");
                }
            });
        }
    }
}
